package com.evry.spring3sandbox.repository;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import javax.sql.DataSource;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.simple.ParameterizedRowMapper;
import org.springframework.jdbc.core.support.JdbcDaoSupport;
import org.springframework.stereotype.Repository;

import com.evry.spring3sandbox.domain.Customer;
import com.evry.spring3sandbox.domain.Order;
import com.evry.spring3sandbox.domain.Product;

@Repository("customerDao")
public class JdbcCustomerDao extends JdbcDaoSupport implements CustomerDao {

	@Autowired
	public JdbcCustomerDao(DataSource dataSource) {
		setDataSource(dataSource);
	}
	
	public void saveCustomer(Customer customer) {

	}

	/** Logger for this class and subclasses */
	protected final Log logger = LogFactory.getLog(getClass());

	public List<Customer> getCustomerList() {
		logger.info("Getting Customers!");
		List<Customer> customers = getJdbcTemplate().query(
				"select id, firstName, lastName, emailaddress from customers",
				new CustomerMapper());
		return customers;
	}


	private static class CustomerMapper implements
			ParameterizedRowMapper<Customer> {

		public Customer mapRow(ResultSet rs, int rowNum) throws SQLException {
			Customer customer = new Customer();
			customer.setId(rs.getInt("id"));
			customer.setFirstName(rs.getString("firstName"));
			customer.setLastName(rs.getString("lastName"));
			customer.setEmailaddress(rs.getString("emailaddress"));
			return customer;
		}

	}

	@Override
	public Customer getCustomerByID(Integer id) {
		logger.info("Get customer by id.");
		List<Customer> customers = getJdbcTemplate().query(
				"select id, firstName, lastName, emailaddress from customers where id = " + id ,
				new CustomerMapper());
		return customers.get(0);
	}
	
	

}